package com.ellecity06.cwhiskymall.ui.address

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.ktx.*
import com.ellecity06.common.widgets.dialog.showAlert
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.adapter.AddressAdapter
import com.ellecity06.cwhiskymall.bean.request.AddressAddRequest
import com.ellecity06.cwhiskymall.databinding.ActivityAddressMannagerBinding
import com.ellecity06.cwhiskymall.ui.address.add.AddressAddActivity

/**
 * @author ellecity06
 * @time 2024/10/31 11:29
 * @des 地址管理
 */
class AddressManagerActivity :
    BaseMvvmActivity<ActivityAddressMannagerBinding, AddressManagerViewModel>(),
    View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {

    private val adapter: AddressAdapter by lazy { AddressAdapter() }
    override fun inflateBinding(): ActivityAddressMannagerBinding {
        return ActivityAddressMannagerBinding.inflate(layoutInflater)
    }

    override fun initialize(savedInstanceState: Bundle?) {
        title = "收货地址"
        binding.refreshLayout.theme()
        binding.rv.adapter = adapter
        binding.rv.layoutManager = LinearLayoutManager(this)
        adapter.isEmptyViewEnable = true
        adapter.setEmptyViewLayout(this, R.layout.layout_empty_view)
        fetchData()
    }

    override fun initEvent() {
        binding.tvAdd.setOnClickListener(this)
        binding.refreshLayout.setOnRefreshListener(this)
        adapter.setOnItemClickListener(::onItemClick)
        adapter.addOnItemChildClickListener(R.id.iv_check, ::onItemClick)
        adapter.addOnItemChildClickListener(R.id.tv_delete, ::onItemClick)
        adapter.addOnItemChildClickListener(R.id.tv_edit, ::onItemClick)
    }

    private fun onItemClick(
        baseQuickAdapter: BaseQuickAdapter<AddressAddRequest, *>,
        view: View,
        i: Int
    ) {
        val item = adapter.getItem(i)
        when (view.id) {
            // 设置默认地址
            R.id.iv_check -> {
                if (item?.isDefault == 1) return
                lifecycleScope.launchWhenCreated {
                    viewModel.intentChannel.send(
                        AddressManagerIntent.SetDefaultAddress(
                            item?.addressId ?: 0
                        )
                    )
                }
            }
            // 删除
            R.id.tv_delete -> {
                showAlert(title = "确认删除地址吗？") {
                    lifecycleScope.launchWhenCreated {
                        viewModel.intentChannel.send(
                            AddressManagerIntent.DeleteAddress(
                                item?.addressId ?: 0
                            )
                        )
                    }
                }

            }
            // 编辑
            R.id.tv_edit -> {
                launchActivityForResult<AddressAddActivity>(
                    ADDRESS_ADD_REQUEST_CODE,
                    Pair("address_id", item?.addressId ?: 0)
                )
            }
        }
    }

    override fun initObserver() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is AddressManagerState.LoadDataError -> {
                    binding.refreshLayout.finishRefresh()
                }
                is AddressManagerState.FetchDataSuccess -> {
                    binding.refreshLayout.finishRefresh()
                    adapter.submitList(it.list)
                }
                else -> {}
            }
        }
    }

    override fun onClick(view: View) {
        when (view.id) {
            binding.tvAdd.id -> {
                launchActivityForResult<AddressAddActivity>(ADDRESS_ADD_REQUEST_CODE)
            }
        }
    }

    companion object {
        private const val ADDRESS_ADD_REQUEST_CODE = 101
    }

    override fun onRefresh() {
        fetchData()
    }

    private fun fetchData() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(AddressManagerIntent.RefreshData)
        }
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == ADDRESS_ADD_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            fetchData()
        }
    }
}